//
//  DVPicplayerView.m
//  QuickCure
//
//  Created by 松鼠君 on 9/12/16.
//  Copyright © 2016 haoge. All rights reserved.
//

#import "DVPicplayerView.h"
#import "ViewController.h"
#import "DVBannerModel.h"
#import "UIImageView+WebCache.h"
@interface DVPicplayerView()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,strong)UICollectionViewFlowLayout* flowlayout;
@property(nonatomic,strong)UIPageControl* pageCt;
@property(nonatomic,strong)NSArray* picPlist;
@property(nonatomic,weak)UICollectionView*  collectionView;
@property(nonatomic,strong)NSTimer* timer;
@end



static  NSString* reusedID = @"cell";

@implementation DVPicplayerView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self initializeForView];
        
    }
    return self;
}




-(void)initializeForView{
    
    
    self. flowlayout  = [UICollectionViewFlowLayout new];
    
    UICollectionView* collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) collectionViewLayout:self.flowlayout];
    

    
    collection.dataSource = self;
    
    collection.delegate = self;
    
    collection.backgroundColor = [UIColor whiteColor];
    
//    UIImageView* imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"2e8611cae3b23686de860402ef338c89"]];
//    
//    imgV.contentMode = UIViewContentModeScaleAspectFit ;
    
    
    
//    collection.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"2e8611cae3b23686de860402ef338c89"]];
    
    
    
    
//    [collection addSubview:imgV];
    
    [self addSubview:collection];
    
    
    
//    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.edges.equalTo(self);
//    }];
    
    
    
    
    collection.pagingEnabled = YES;
    
    collection.bounces = NO;
    
    [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reusedID];
    
    
    self.collectionView = collection;
    
    
    
    
    UIPageControl* pageCt = [UIPageControl new];
    
    pageCt.numberOfPages = 3;
    
    self.pageCt = pageCt;
    
    [self addSubview:pageCt];
    
    
    [pageCt  mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self).offset(-30);
        
        make.bottom.equalTo(self).offset(-10);
        
        make.size.mas_equalTo(CGSizeMake(60, 50));
        
    }];
    
    
    /**
     *  定时器
     *
     */
    
    
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(play) userInfo:nil repeats:YES];
    
    self.timer = timer;
    
    [timer fire];
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    
    
    

    
    CGPoint  p  = self.collectionView.contentOffset;
    
    
    p.x  =  self.picPlist.count*self.bounds.size.width;
    
    
    [self.collectionView setContentOffset:p];
    
    
    
    /**
     *  屏蔽滚动条
     *
     *
     */
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    
    
}

#pragma mark
#pragma mark "图片数据懒加载"

-(NSArray*)picPlist{
    
    
    if (!_picPlist) {
        
        
        
        [self fecthDataWithBlock:^(id responseObject) {
         
            
            NSDictionary* rootDic = responseObject;


            NSDictionary* dic = rootDic[@"data"];
            
            NSArray* bannersArr = dic[@"banners"];
            
            NSMutableArray* arr = [NSMutableArray array];

            
            [bannersArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                
                DVBannerModel * bannerModel = [DVBannerModel new];
                
                [bannerModel setValuesForKeysWithDictionary:obj];
                
                [arr addObject:bannerModel];
                
            }];
            
            _picPlist = arr.copy;
            

            
            [self.collectionView reloadData];
    
            
            
        }];
        

    }
    
    
    return _picPlist;
    
}


-(void)fecthDataWithBlock:(void(^)(id responseObject))block{

    
    NSString *urlString = kBannersUrl;
    NSDictionary *paramDic = @{
                               @"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",
                               @"page_size":@10,
                               @"page":@1};
    
    
    NSURLSessionConfiguration* confi = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:confi];
    
    
    // 更改默认序列化方式
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    
    [manager POST:urlString parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (block) {
            block(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
//        NSLog(@" error  = %@",error);
        
    }];

    
    
}

    


-(void)layoutSubviews{
    
    // 设置成 self.bounds.size 会不匹配
    self.flowlayout.itemSize = self.collectionView.bounds.size;
    
    self.flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.flowlayout.minimumLineSpacing = 0;
    
    self.flowlayout.minimumInteritemSpacing = 0;
    
    
    
}


#pragma mark
#pragma mark "collection 的 代理方法"



- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.picPlist.count;
    
//    return 3;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    DVBannerModel* bannerModel = self.picPlist[indexPath.row];
    
    UICollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:reusedID forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    UIImageView* imgV = [UIImageView new];
    
    [cell addSubview:imgV];
    
//    imgV.image = [UIImage imageNamed:@"2e8611cae3b23686de860402ef338c89"];
    
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(cell).mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [imgV sd_setImageWithURL:bannerModel.imageArray[indexPath.row]];
        
    
    return cell;
    
}

-(void)play{
    
    
    if (self.collectionView.contentOffset.x == self.collectionView.contentSize.width - self.collectionView.bounds.size.width ) {
        
        [self.collectionView setContentOffset:CGPointZero animated:YES];
        
        return;
        
    }
    
    CGPoint locationPoint = self.collectionView.contentOffset;
    
    locationPoint.x+=self.collectionView.bounds.size.width;
    
    [self.collectionView setContentOffset:locationPoint animated:YES];
    

    
    
}


-(void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    
    [self.timer invalidate];
    
    self.timer = nil;
    
    //    NSLog(@"%s",__func__);

    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    self.pageCt.currentPage =  (scrollView.contentOffset.x+self.bounds.size.width/2)/(self.bounds.size.width);
    
    NSInteger a =   (scrollView.contentOffset.x+self.bounds.size.width/2);
    NSInteger b = (self.bounds.size.width);
    self.pageCt.currentPage = (a/b)%3;
    

    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2  * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(play) userInfo:nil repeats:YES];
        
        self.timer = timer;
        
        [timer fire];
        
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

//    });


    
    
    
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    
    
    NSIndexPath* indexPath =   [self.collectionView indexPathForItemAtPoint:self.collectionView.contentOffset];
    
    
    if (indexPath.section != 1&& indexPath) {
        
        
        NSIndexPath* index  = [NSIndexPath indexPathForRow:indexPath.row inSection:1];
        
        [self.collectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        
        
    }
    

}




@end
